import com.sun.xml.internal.ws.addressing.WsaActionUtil;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: XMQ
 * Date: 2022-06-05
 * Time: 15:31
 */
public class MyArrayList {

    public int[] elem;
    public int DEFAULT_CAPACITY = 2;
    public int usedSize = 0;

    public MyArrayList(){
        this.elem = new int[DEFAULT_CAPACITY];
    }

    //打印顺序表
    public void display(){
        for (int i = 0; i < usedSize; i++) {
            System.out.print(elem[i] + " ");
        }
        System.out.println();

    }

    //判满
    private boolean isFull(){
        if(usedSize == elem.length){
            return true;
        }
        return false;
    }

    //尾插
    public void add(int data){
        if(isFull()){
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize++] = data;
    }

    //在任意位置插入
    public void add(int pos,int data){
        if(isFull()){
            elem = Arrays.copyOf(elem,2*elem.length);
        }
        for (int i = usedSize; i > pos; i--) {
            elem[i] = elem[i-1];
        }
        elem[pos] = data;
        usedSize++;
    }

    //尾删
    public void del(){
        if(usedSize == 0 || elem == null) return;
        elem[usedSize] = 0;
        usedSize--;
    }

    //删除任意位置的数
    public void del(int pos){
        try{
            for (int i = pos; i < usedSize-1; i++) {
                elem[i] = elem[i+1];
            }
            usedSize--;
        }catch (ArrayIndexOutOfBoundsException e){
            e.printStackTrace();
            System.out.println("输入的下标属于非法位置");
        }
    }

    //修改某个位置的数据
    public void set(int pos,int data){
        try{
            for (int i = 0; i < usedSize; i++) {
                if(i == pos){
                    elem[i] = data;
                }
            }
        }catch (ArrayIndexOutOfBoundsException e){
            e.printStackTrace();
            System.out.println("输入的下标属于非法位置");
        }
    }

    //获取pos位置的元素
    public int get(int pos){
        try{
            return elem[pos];
        }catch (ArrayIndexOutOfBoundsException e){
            e.printStackTrace();
            System.out.println("输入的下标属于非法位置");
            return -1245123145;
        }
    }
    //获取某个数据的位置
    public int indexOf(int data){
        for (int i = 0; i < usedSize; i++) {
            if(elem[i] == data){
                return i;
            }
        }
        return -1;
    }

    //获取顺序表的长度
    public int size(){
        return usedSize;
    }
    //清除数据
    public void clear() {
        for (int i = usedSize - 1; i >= 0; i--) {
            elem[i] = 0;
            usedSize--;
        }
    }
}
